
<template>
<!-- 设备信息页面 -->
    <div class="wrapper">
        <div class="header">
            <el-row style="margin-bottom:20px">
                <el-button type="danger" style="width:120px" @click="add">新建</el-button>
            </el-row>
             <el-row>
                <el-col :span="4" style="margin-right:30px">
                    <el-input placeholder="设备ID" v-model="quickSearchVal"></el-input>
                </el-col> <el-button type="danger" style="width:120px" @click="getList">查询</el-button>
            </el-row>
        </div>
        <div class="body">
            <el-row class="container">
                <el-col :span="6" v-for="(item,index) in list" :key="index" class="item-box">
                    <div class="img-box">
                        <div class="content">
                            <img :src="item.img?item.img:showImg(item.status)" alt="" style="width:100%;height:100%">
                        </div>
                    </div>
                    <div class="word-box">
                        <p>
                            设备ID：{{item.id}}
                        </p>
                         <p>
                            设备状态：{{item.status ==0 ?"未连接":"连接"}}
                        </p>
                         <p>
                            脚本执行状态：{{item.commandStatus.commandStatus=="running"?'执行中':'未执行'}}
                        </p>
                         <p>
                            脚本执行情况(成功数/总数)：{{item.commandStatus.successCount}}/{{item.commandStatus.totalCount}}
                        </p>
                    </div>
                    <div class="btn-box">
                        <el-button size="mini" :disabled='item.status !=0' @click="edit(item)">修改</el-button>
                        <el-button size="mini" :disabled='item.status !=0' @click="del(item)">删除</el-button>
                        <el-button :disabled="item.disabled || item.status != 1" size="mini" @click="startTask(item)">{{item.commandStatus.commandStatus =='stop'?"脚本执行":"停止执行"}}</el-button>
                    </div>
                </el-col>
            </el-row>
        </div>
        <!-- 新增/修改弹窗 -->
        <el-dialog
            :title="titleType =='add'?'新增':'修改'"
            :visible.sync="centerDialogVisible"
             :before-close="onCancel"
            width="30%"
            >
            <div>
                <el-form ref="addForm" :model="addForm" :rules="rule" label-position="right" label-width="80px">
                    <el-form-item label="设备ID" prop='id'>
                        <el-input :readonly="titleType =='edit'" v-model="addForm.id" placeholder="请输入设备ID"></el-input>
                    </el-form-item>
                    <el-form-item label="设备别名" prop='name'>
                        <el-input v-model="addForm.name" placeholder="请输入设备别名"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop='remark'>
                        <el-input v-model="addForm.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="onCancel">取 消</el-button>
                <el-button type="primary" @click="onOk">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 脚本执行弹窗 -->
        <el-dialog 
            :visible.sync="visible"
            width="500px"
            >
            <div>
                <el-form ref="moveData" :model="moveData" :rules="rule" label-position="right" label-width="80px">
                    <el-form-item label="执行脚本" prop='taskId'>
                        <!-- <el-input v-model="moveData.scrpit" placeholder="请选择执行脚本"></el-input> -->
                         <el-select clearable v-model="moveData.taskId" placeholder="请选择执行脚本">
                            <el-option
                            v-for="item in content"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="" prop='time'>
                        <el-radio v-model="moveData.time" :label="1">单次执行</el-radio>
                        <el-radio v-model="moveData.time" :label="2">多次执行</el-radio>
                    </el-form-item>
                    <el-form-item label="执行次数" prop='count' v-if="moveData.time==2"> 
                        <el-input-number :min="1" v-model.number="moveData.count" placeholder="请输入执行次数"></el-input-number>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="onCancel">取 消</el-button> -->
                <el-button type="primary" @click="moveOk">运行</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { facilityInfoList,facilityInfoStart,
    facilityInfoStop,facilityInfoUpdate,
    facilityInfoDel,facilityInfoAdd,scriptList,scriptStart,scriptStop
     } from '../../../api/facility/index'
    import { getToken } from '../../../utils/auth'
     import Socket from '../../../utils/socket'
export default {
    data () {
        return {
            titleType:'add',
            centerDialogVisible:false,
            visible:false,
            list:[],
            pageSize:20,
            pageNum:1,
            items:{},
            quickSearchVal:'',

            addForm:{
                id:'',
                name:'',
                remark:''
            },
            rule:{
                id:[  { required: true, message: '请输入设备ID', trigger: 'blur' },],
                 name:[  { required: true, message: '请输入设备别名', trigger: 'blur' },],
                  remark:[  { required: true, message: '请输入备注', trigger: 'blur' },]
            },
            moveData:{
                deviceId:'',
                taskId:'',
                count:'',
                time:''
            },
             searchBo:{},
             socket:null,
             content:[]
        }
    },
    mounted () {
        this.getList();
        scriptList({
            pageNum:1,
            pageSize:0
        }).then(res=>{
            if(res.status =='200'){
                this.content = [...res.data.list]
            }
        });
        this.socket = new Socket({url:'ws://192.168.5.42:15971/device-client/'+getToken(),callback:this.onMessage})

    },
    destroyed () {
        this.socket.close()
    },
    methods:{
        startTask(item) {
            console.log(item)
            if(item.commandStatus.commandStatus == 'stop'){
                this.visible=true;this.items=item;
            }else{
                this.stopTask(item)
            }
             
        },
        stopTask (item) {
            scriptStop({deviceId:item.id}).then(res=>{
                if(res.status ==200){
                    this.$message({
                        type:"success",
                        message:'脚本停止执行成功！'
                    })
                    this.list.map(res=>{
                        if(res.id == item.id){
                            res.commandStatus.successCount = 0;
                               res.commandStatus.totalCount = 0;
                               res.commandStatus.commandStatus = 'stop'
                        }
                    })
                    this.list = [...this.list]
                }else{
                    this.$message(res.msg)
                }
            })
        },
        onOk () {
            this.$refs['addForm'].validate((vaild)=>{
                if(vaild) {
                    if(this.titleType =='add'){
                        //新增
                        facilityInfoAdd(this.addForm).then(res=>{
                            if(res.data){
                                this.getList();
                                this.$message.success('新增成功！')
                            } else {
                                this.$message(res.msg)
                            }
                        })
                    }else {
                        //编辑
                        
                        facilityInfoUpdate(this.addForm).then(res=>{
                           if(res.data){
                                this.getList();
                                this.$message.success('修改成功！')
                            } else {
                                this.$message(res.msg)
                            }
                        })
                    }

                    this.onCancel()
                }
            })
           
        },
        onCancel () {
            this.centerDialogVisible = false;
            this.$refs['addForm'].clearValidate();
            this.$refs['addForm'].resetFields();
            this.addForm = this.$options.data().addForm
        },
        showImg (data) {
            if(data == 1) {
                return require('../../../../src/assets/img/online.jpg')
            }else {
                return require('../../../../src/assets/img/offline.jpg')
            }
        },
        moveOk () {
            
            let obj ={
                deviceId:this.items.id,
                count:this.moveData.time == 2?this.moveData.count:this.moveData.time,
                taskId :this.moveData.taskId
            }
            scriptStart(obj).then(res=>{
                if(res.status == 200){
                    this.$message({
                        type:'success',
                        message:'脚本正在执行中'
                    })

                }
                this.list.map(item=>{
                    if(item.id == this.items.id){
                        item.commandStatus.commandStatus = 'running';
                    }
                })
                this.list = [...this.list]
            }).finally(res=>{
                this.visible = false;
                this.moveData = this.$options.data().moveData;
            })
        },
        /* 列表 */
        getList () {
            let obj ={
               pageSize:this.pageSize,
               pageNum:this.pageNum ,
               id:this.quickSearchVal
            }
            facilityInfoList(obj).then(res=>{
                if(res.msg == 'success'){
                    this.list = res.data.list
                }else {
                    this.$message(res.msg)
                }
            })
        },
        onMessage (data) {
            var data = JSON.parse(data)
            this.list.map (item => {
                if(item.id == data.messageData.deviceId){
                    switch (data.messageType){
                        case 'online':
                            item.status = 1;
                            break;
                        case 'offline': 
                            item.status = 0;
                            break;

                        case 'heart':
                            
                            item.img = data.messageData.data.screenImg;
                            break
                        case 'command_result' :
                            item.commandStatus.successCount = data.messageData.data.successCount;
                            item.commandStatus.totalCount = data.messageData.data.totalCount
                            if(data.messageData.data.successCount + data.messageData.data.failCount == data.messageData.data.totalCount){
                                
                            //    item.disabled = false;
                               item.commandStatus.successCount = 0;
                               item.commandStatus.totalCount = 0;
                               item.commandStatus.commandStatus = 'stop'
                            //    this.list = [...this.list]
                            }else{
                                // item.disabled = true;
                            }
                            break;
                    }
                }
            })
            this.list = [...this.list]
            console.log(data)
        },
        /* 快速查询 */
       
        /* 编辑按钮 */
        edit (item) {
            this.addForm = {...item};
            this.centerDialogVisible=true;
            this.titleType='edit'
        },
        /* 新增按钮 */
        add () {
            this.centerDialogVisible=true;this.titleType='add'
        },
        /* 删除按钮*/
        del (item) {
            this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    facilityInfoDel(item).then(res=>{
                        if(res.data) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getList()
                        }else{
                            this.$message({
                                type:'error',
                                message:res.msg
                            })
                        }
                    })
                    
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        }
    }
}
</script>

<style lang="less" scoped>
    .wrapper{
        width: 100%;
         overflow: auto;
        //  padding-bottom: 50px;
        //  box-sizing: border-box;
        .header{
            height: 190px;
            margin-bottom: 25px;
            background-color: #fff;
            padding:38px 20px;
            box-sizing: border-box;;
        }
        .body{
            width: 100%;
            height:500px ;
            overflow: auto;
            padding-left:50px;
            padding-bottom: 50px;
            box-sizing: border-box;
            background-color: #fff;
            .container {
                .item-box{
                    margin-top:25px;

                    .img-box{
                    background-image: url('../../../assets/img/phone.jpg');
                    background-repeat: no-repeat ;

                    background-size:100% 100%;
                        width:120px;
                        height: 245px;
                        margin-bottom: 20px;
                        position: relative;
                        background-color: #dadada;
                        border-radius: 15px;
                        position: relative;
                        .content{
                            width:104px;
                            height: 186px;
                            position: absolute;
                            left:0;right: 0;top:0;bottom: 0;
                            margin:auto;
                            overflow: hidden;

                        }
                    }
                    .word-box {
                         margin-bottom: 20px;
                        font-size: 12px;
                        color:#101010;
                    }
                }
            }
        }

    }
</style>